package com.example.springfeature.createobject;

import java.io.*;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IDEA
 *
 * @author: 董文辉
 * Date: 2019/3/1
 * Time: 11:03
 */
public class CreateObjectTest {
    private static final String USER_OBJECT_FILE_NAME= "userObjectFile";
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, CloneNotSupportedException, NoSuchMethodException, InvocationTargetException, IOException {
        //方法一：new 关键字
        User user = new User(); //结果：调用空参构造创建对象
        //方法二：反射 Class.newInstance
        User user1 = User.class.newInstance(); //结果：调用空参构造创建对象
        //方法三：clone
        User clone = (User)user.clone();  //结果：调用jvm复制对象
        //方法四：Constructor类的newInstance方法 //结果：调用空参构造创建对象
        User user4 = User.class.getConstructor().newInstance();
        //方法五：使用序列化创建
        user.setIsTrue("yes");
        user.setName("ddd");
        writeObject(user);
        User o = readObject(USER_OBJECT_FILE_NAME, User.class);
        System.out.println(o);
    }

    private static void writeObject(User user) throws IOException {
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream(USER_OBJECT_FILE_NAME));
            out.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            out.close();
        }
    }

    private static  <T> T readObject(String fileName,Class<T> className) throws IOException {
        ObjectInputStream ints = null;
        try {
            ints = new ObjectInputStream(new FileInputStream(USER_OBJECT_FILE_NAME));
            try {
                Object o = ints.readObject();
                T cast = className.cast(o);
                return  cast;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            ints.close();
        }
        return null;
    }
}
